package lc.com.lcpicturebackend.manager.upload;

import cn.hutool.core.io.FileUtil;
import lc.com.lcpicturebackend.exception.ErrorCode;
import lc.com.lcpicturebackend.exception.ThrowUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

import static lc.com.lcpicturebackend.constant.FileConstant.ALLOW_FORMAT_LIST;
import static lc.com.lcpicturebackend.constant.FileConstant.ONE_M;

/**
 * 功能：文件上传
 * 作者：lc
 * 日期：2025/1/17 2:17
 */
@Service
public class FilePictureUpload extends PictureUploadTemplate {
    @Override
    protected void validPicture(Object inputSource) {
        MultipartFile multipartFile = (MultipartFile) inputSource;
        // 1.校验参数
        ThrowUtils.throwIf(multipartFile == null,
                ErrorCode.PARAMS_ERROR, "文件不能为空");
        // 2.校验文件大小
        ThrowUtils.throwIf(multipartFile.getSize() > 2 * ONE_M,
                ErrorCode.PARAMS_ERROR, "文件大小不能超过2M");
        // 3.校验文件类型
        // 文件类型后缀
        String fileSuffix = FileUtil.getSuffix(multipartFile.getOriginalFilename());
        ThrowUtils.throwIf(!ALLOW_FORMAT_LIST.contains(fileSuffix),
                ErrorCode.PARAMS_ERROR, "仅支持上传jpg,jpeg,png,webp文件！");

    }

    @Override
    protected String getOriginFilename(Object inputSource) {
        MultipartFile multipartFile = (MultipartFile) inputSource;
        return multipartFile.getOriginalFilename();

    }

    @Override
    protected void processFile(Object inputSource, File file) throws IOException {
        MultipartFile multipartFile = (MultipartFile) inputSource;
        multipartFile.transferTo(file);
    }
}
